package system

import (
	"5title_gin/internal/api/middleware"
	"5title_gin/internal/model/system/dept"
	"5title_gin/internal/service/system"
	"5title_gin/pkg/utils/http"
	"github.com/gin-gonic/gin"
)

type DeptAPI struct {
	service *system.DeptService
}

func NewDeptAPI() *DeptAPI {
	return &DeptAPI{
		service: system.NewDeptService(),
	}
}

type QueryDept struct {
	ID uint `binding:"required" json:"id" label:"id"`
}

// CreateDept 创建部门
// @Tags 部门管理
// @Summary 创建部门
// @Description 创建一个新的部门
// @Param token header string true "token"
// @Param data body dept.SysDept true "部门信息"
// @Router /api/dept/create [post]
// @Produce json
// @Success 200 {object} http.Response

func (api *DeptAPI) CreateDept(c *gin.Context) {
	// 解析请求数据
	deptData := middleware.GetBind[dept.SysDeptBo](c)
	msg, err := api.service.CreateDept(deptData)
	if err != nil {
		http.FailWithMsg(msg, c)
		return
	}
	// 返回成功响应
	http.OkWithMsg(msg, c)
}

// GetDeptList 获取部门列表
func (api *DeptAPI) GetDeptList(c *gin.Context) {
	list, err := api.service.GetDeptList()
	if err != nil {
		http.FailWithMsg("获取部门列表失败", c)
		return
	}
	http.OkWithData(list, c)
}

// GetDeptByID 获取单个部门信息
func (api *DeptAPI) GetDeptByID(c *gin.Context) {
	cr := middleware.GetBind[QueryDept](c)
	department, err := api.service.GetDeptInfo(cr.ID)
	if err != nil {
		http.FailWithMsg("获取部门信息失败", c)
		return
	}
	http.OkWithData(department, c) // 这里返回查询到的具体数据
}

// UpdateDept 更新部门信息
func (api *DeptAPI) UpdateDept(c *gin.Context) {
	cr := middleware.GetBind[dept.SysDeptBo](c)
	if err := api.service.UpdateDept(cr); err != nil {
		http.FailWithMsg("更新部门信息失败", c)
	}
	http.OkWithMsg("更新部门信息成功", c)
}

// DeleteDept 删除部门
func (api *DeptAPI) DeleteDept(c *gin.Context) {
	cr := middleware.GetBind[QueryDept](c)
	if err := api.service.DeleteDept(cr.ID); err != nil {
		http.FailWithMsg("删除部门失败", c)
		return
	}
	http.OkWithMsg("删除部门成功", c)
}

// GetDeptOptions 获取上级部门列表(树形结构)
func (api *DeptAPI) GetDeptOptions(c *gin.Context) {
	selector, err := api.service.GetDeptTreeSelector()
	if err != nil {
		http.FailWithMsg("获取下拉框数据失败", c)
		return
	}
	http.OkWithData(selector, c)
}
